<template>
  <div class='directorys-add'>
    <!-- 新增目录弹出层 -->
    <el-dialog
      :title="this.addForm.id ?'修改目录': '新增目录'"
      :visible="addDialog"
      width="30%"
      @close="btnCancel"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="所属学科" prop="subjectName" v-if="!$route.query.id">
          <el-select
            style="width: 80%"
            placeholder="请选择"
            v-model="addForm.subjectName"
            @change="selectChange"
          >
            <el-option
              v-for="item in subjectNameList"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input
            style="width: 80%"
            v-model="addForm.directoryName"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="btnCancel">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/directorys.js'

export default {
  name: 'AddDirectorys',
  props: {
    addDialog: {
      type: Boolean,
      default: false
    },
    subjectNameList: {
      type: Array,
      required: true
    },
    subjectID: {
      type: String,
      default: null
    }

  },
  data () {
    return {
      addForm: {
        subjectName: '',
        directoryName: '',
        subjectID: this.subjectID,
        id: ''
      },
      addFormRules: {
        directoryName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    selectChange (val) {
      this.addForm.subjectID = val
    },
    btnOk (id) {
      this.$refs.addFormRef.validate(async (isOk) => {
        if (isOk) {
          if (!this.addForm.id) {
            await add({ subjectID: Number(this.addForm.subjectID), directoryName: this.addForm.directoryName })
            this.$message.success('新增目录成功')
          } else {
            await update(this.addForm)
            this.$message.success('修改目录成功')
          }
          this.$emit('addDir')
          this.$parent.addDialog = false
          this.btnCancel()
        }
      })
    },
    btnCancel () {
      this.addForm = {
        subjectName: '',
        directoryName: '',
        subjectID: this.subjectID,
        id: ''
      }
      this.$refs.addFormRef.resetFields()
      this.$parent.addDialog = false
    }
  }
}
</script>

<style scoped lang='less'></style>
